package com.hsogoo.collate.batch;

import com.hsogoo.collate.constants.Constant;
import com.hsogoo.collate.domain.CollateRecord;
import com.hsogoo.collate.mapper.CollateRecordMapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

import java.util.Random;

/**
 * @Author huangsaigang
 * Created @2019-10-28.
 */
@Slf4j
@Setter
public class RecordCollateTasklet implements Tasklet {

    private CollateRecordMapper collateRecordMapper;

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
        log.info("RecordCollateTasklet.executing...");
        JobParameters jobParameters = stepContribution.getStepExecution().getJobExecution().getJobParameters();
        String taskName = jobParameters.getString("taskName");
        String collateDate = jobParameters.getString("targetCollateDate");
        String collateFile = jobParameters.getString("targetCollateFile");
        //前面CollateJobLauncher已经校验过了
        CollateRecord collateRecord = new CollateRecord();
        collateRecord.setTaskName(taskName);
        collateRecord.setCollateDate(collateDate);
        collateRecord.setCollateFile(collateFile);
        collateRecord.initTime();
        Long recordId = collateRecordMapper.addCollateRecord(collateRecord);
        stepContribution.getStepExecution().getExecutionContext().put("recordId", collateRecord.getId());
        stepContribution.getStepExecution().getExecutionContext().put("executedFlag", Constant.TASK_NEW_EXECUTE);
        log.info("RecordCollateTasklet recorded with id {}", recordId);
        return RepeatStatus.FINISHED;
    }
}
